I tried Remote State And State Locking in Terraform Using S3

I tried Remote State And State Locking in Terraform Using S3

Clock Icon2022.09.21

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

Why is the tfstate file necessary?

  1. One advantage of the terraformed state is the ability for TerraForm to build and delete resources in the proper sequence by tracking dependencies and mapping Terraform configuration to real-world infrastructure.

  2. enhancing TerraForm operations performance while working with big configuration files, particularly those that employ several cloud providers.

  3. The TerraForm state enables team members to communicate and provide resources together.

What is a Remote State?

With a remote state, Terraform writes the state data to a remote data store, which can be shared between all team members.

Terraform Remote State Storage Options

Terraform supports storing state in

  1. Amazon S3
  2. Azure Blob Storage
  3. Google Cloud Storage
  4. Terraform Cloud
  5. HashiCorp Consul
  6. Many more.

Pre-requisite:

1.S3 bucket, which will be used to store data from the state file. 2. Dynamo DB table, which will be used to implement state locking and consistency checks. Use this terraform for creating the same

provider "aws" {
 region  = "ap-northeast-1"
 shared_credentials_file = "~/.aws/credentials"
}
 
resource "aws_s3_bucket" "tf_course" { 
   bucket = "deviostatefile"
   acl = "private"
}
 
 
resource "aws_dynamodb_table" "dynamodb-terraform-state-lock" {
 name = "terraform-state-lock-dynamo"
 hash_key = "LockID"
 read_capacity = 20
 write_capacity = 20
 attribute {
   name = "LockID"
   type = "S"
 }
}

Note: A. bucket name, B. the key to be used, C. the region D.the name of the DynamoDb Table

Remote state setup can be achieved by setting up backends specific to the cloud.

Setting up a remote state in Amazon S3:

backend.tf

terraform {
 backend "s3" {
   bucket         = "deviostatefile"
   dynamodb_table = "terraform-state-lock-dynamo"
   key            = "prod_terraform.tfstate"
   region         = "ap-northeast-1"
 }
}

After terraform Apply:

  1. we can verify the state file stored in remote location [Amazon s3]
2. we can verify state Lock error

Conclusion :

This hands on will help teams to collaborate more efficiently. Developers and engineers will work without worrying about loosing and corrupting there tfstate file hope this blog helps

Reference :

https://dev.classmethod.jp/articles/integrate-terraform-remote-state-hub/ https://www.terraform.io/language/state/remote-state-data

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.